// ==UserScript==
// @name         替换脚本
// @namespace    https://bbs.tampermonkey.net.cn/
// @version      0.1.0
// @description  替换特定脚本的 src
// @author       You
// @match        https://www.xiaohongshu.com/*
// @run-at       document-start
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    const targetScript = 'vendor-dynamic.3293d643.js';
    const replacementUrl = 'https://cdn.jsdelivr.net/gh/StutteringBoy/jsReverseFile@main/vendor-dynamic.3293d643.js';

    // 覆盖所有脚本插入方式
    const originalAppendChild = Element.prototype.appendChild;
    Element.prototype.appendChild = function (node) {
        if (node.tagName === 'SCRIPT' && node.src.includes(targetScript)) {
            node.src = replacementUrl;
            node.onload = () => console.log('替换脚本已加载:', replacementUrl);
        }
        return originalAppendChild.apply(this, [node]);
    };

    const originalInsertBefore = Element.prototype.insertBefore;
    Element.prototype.insertBefore = function (node, beforeNode) {
        if (node.tagName === 'SCRIPT' && node.src.includes(targetScript)) {
            node.src = replacementUrl;
            node.onload = () => console.log('替换脚本已加载:', replacementUrl);
        }
        return originalInsertBefore.apply(this, [node, beforeNode]);
    };

    // 覆盖 document.write 插入脚本
    const originalWrite = document.write;
    document.write = function (text) {
        if (typeof text === 'string' && text.includes(targetScript)) {
            text = text.replace(targetScript, replacementUrl);
        }
        return originalWrite.apply(document, [text]);
    };

    // 替换已存在的 script 标签（防止单次加载后被缓存）
    const existingScripts = document.querySelectorAll(`script[src*="${targetScript}"]`);
    existingScripts.forEach(script => {
        const newScript = document.createElement('script');
        newScript.src = replacementUrl;
        newScript.onload = () => console.log('替换脚本已加载:', replacementUrl);
        script.parentNode.replaceChild(newScript, script);
    });
})();